<template>
  <div class="app-container">
    <div v-show="!receiptModifyInfo.visible && !receiptDetailsInfo.visible">
      <!-- 条件栏 -->
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-retract>
          <el-button :disabled="canRatify" @click="retract()">撤回</el-button>
        </template>
        <template v-slot:filter-ratify>
          <el-button :disabled="canRatify" @click="ratify()">批准</el-button>
        </template>
        <template v-slot:filter-consumeTime>
          <el-date-picker
            @change="timeChange"
            v-model="time"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            :shortcuts="$fn.pickerOptionsFn()"
            align="right"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59),
            ]"
          ></el-date-picker>
        </template>
      </page-filter>

      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="getReceiptBillPage"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :tabIndex="false"
        :check-box="true"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-billCode="scope">
          <p
            class="slip-edit"
            v-if="$permission('receipt:details')"
            @click="showDetail(scope.row)"
          >
            {{ scope.row.billCode || '-' }}
          </p>
          <span v-else>{{ scope.row.billCode || '-' }}</span>
        </template>
      </table-container>
    </div>
    <modify
      v-if="receiptModifyInfo.visible"
      v-model:visible="receiptModifyInfo.visible"
      :title="receiptModifyInfo.title"
      :id="receiptModifyInfo.id"
      @returnModify="returnModify"
    />
    <receiptdetails
      v-if="receiptDetailsInfo.visible"
      v-model:visible="receiptDetailsInfo.visible"
      :title="receiptDetailsInfo.title"
      :id="receiptDetailsInfo.id"
      @returnBack="getList"
    />
  </div>
</template>
<script setup name="receipt">
import PageFilter from '@/components/PageFilter/index'
import TableContainer from '@/components/TableContainer/index'
import modify from './modify'
import receiptdetails from './details'
import {
  downloadFileBillRegistration,
  getReceiptBillPage,
  submitBillRegistration, //提交
  retractBillRegistration, //撤回
  ratifyBillRegistration, //批准
  rejectBillRegistration, //驳回
  removeBillRegistration, //删除
  resetBillRegistration, //重置
} from '../../../api/receipt.js'
import { getSupplierAll } from '@/api/core'
const { proxy } = getCurrentInstance()

const depotId = ref('')
const time = ref([])
// 相关列表
const listTypeInfo = reactive({
  depotList: [],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    sort: 'create_time desc',
    supplierAuth: 'collectOrgId',
    createTimeGreater: '',
    createTimeLess: '',
  },
  list: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('receipt:add'),
      event: create,
    },
    {
      type: 'slot',
      label: '批准',
      value: 'ratify',
      show: proxy.$permission('receipt:ratify'),
    },
    {
      type: 'slot',
      label: '撤回',
      value: 'retract',
      show: proxy.$permission('receipt:retract'),
    },
    // {type: 'slot', label: '驳回', value: 'reject'},
    {
      type: 'button',
      label: '下载附件',
      event: downloadFile,
      show: proxy.$permission('receipt:downloadFile'),
    },
    {
      label: '供应商',
      value: 'collectOrgId',
      type: 'slip-select',
      api: getSupplierAll,
      query: { supplierAuth: 'supplierId', sort: 'create_time desc' },
      clearable: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      event: search,
    },
    { label: '创建时间', value: 'consumeTime', type: 'slot' },
    {
      type: 'input',
      label: '发票单号',
      value: 'OrBatchLike#billCode#billNumber',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})

// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  tabIndex: true,
  fieldList: [
    { label: '收票单号', value: 'billCode', type: 'slot' },
    { label: '收款单位', value: 'collectOrgName' },
    { label: '开票日期', value: 'billDate' },
    { label: '经手人', value: 'operator' },
    {
      label: '票面金额(元)',
      value: 'billAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    { label: '发票号码', value: 'billNumber' },
    { label: '状态', value: 'statusValue' },
    { label: '创建时间', value: 'createTime' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    //完成4-驳回3-待审核2-待提交1
    btList: [
      {
        label: '删除',
        event: remove,
        show: proxy.$permission('receipt:remove'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('receipt:update'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('receipt:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: retract,
        show: proxy.$permission('receipt:retract'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '批准',
        event: ratify,
        show: proxy.$permission('receipt:ratify'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('receipt:reject'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '重置',
        event: reset,
        show: proxy.$permission('receipt:reset'),
        ifRender: function (row) {
          return row.status === 4
        },
      },
    ],
  },
})
const receiptModifyInfo = reactive({
  id: '',
  visible: false,
  title: '',
})
const receiptDetailsInfo = reactive({
  id: '',
  visible: false,
})

watch(
  () => filterInfo.query.createTimeGreater,
  (val) => {
    if (!val) {
      time.value = null
    }
  }
)

const canRatify = computed(() => {
  return (
    tableInfo.selections.filter((item) => item.status !== 2).length !== 0 ||
    tableInfo.selections.length === 0
  )
})

function downloadFile() {
  downloadFileBillRegistration(filterInfo.query).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (receiptModifyInfo.id) {
    getList()
  } else {
    search()
  }
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
//新增
function create() {
  receiptModifyInfo.id = ''
  receiptModifyInfo.visible = true
  receiptModifyInfo.title = '新增收票登记'
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  receiptDetailsInfo.visible = true
  receiptDetailsInfo.id = row.id
}
function update(row) {
  // 修改
  sessionStorage.setItem('storeRowId', row.id)
  receiptModifyInfo.id = row.id
  receiptModifyInfo.title = '修改收票登记'
  receiptModifyInfo.visible = true
}
function submit(row = undefined) {
  //提交
  let ids = [row.id]
  submitBillRegistration(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function ratify(row = undefined) {
  //批准
  let ids = getSelectionIds(row)
  ratifyBillRegistration(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function retract(row = undefined) {
  //撤回
  let ids = getSelectionIds(row)
  retractBillRegistration(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function remove(row = undefined) {
  //删除
  let ids = [row.id]
  removeBillRegistration(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function reject(row = undefined) {
  //驳回
  proxy
    .$prompt('驳回理由', '收票登记', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^[\S]+/,
      inputErrorMessage: '请输入驳回理由',
    })
    .then(({ value }) => {
      const data = {
        id: row.id,
        rejectReason: value,
      }
      rejectBillRegistration(data).then((resp) => {
        if (resp && resp.success) {
          _getList()
        }
      })
    })
    .catch(() => {})
}
function reset(row) {
  //重置
  proxy
    .$confirm('此操作将更新数据, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let ids = getSelectionIds(row)
      resetBillRegistration(ids).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
    .catch((e) => {})
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}
function getSelectionIds(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map(function (item) {
      return item.id
    })
  }
  return ids
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.query.createTimeGreater = val[0]
    filterInfo.query.createTimeLess = val[1]
  } else {
    filterInfo.query.createTimeGreater = ''
    filterInfo.query.createTimeLess = ''
  }
}
</script>
<style scoped></style>
